package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

import model.Role;
import dao.RoleDAO;

public class RoleDAOImpl implements RoleDAO {

	private DBUtil dbu = new DBUtil();
	private Connection conn = null;
	private PreparedStatement pstat = null;
	private ResultSet rs = null;
	
	public List<Role> getAll() {
		List<Role> list=new ArrayList<Role>();
		try{
			String sql="select * from role";
			conn=dbu.getConnection();
			pstat=conn.prepareStatement(sql);
			rs=pstat.executeQuery();
			while(rs.next()){
				Role role=new Role();
				role.setId(rs.getInt("ID"));
				role.setName(rs.getString("NAME"));
				list.add(role);
			}
		}catch (Exception e) {
			System.out.println("返回所有role数据库连接出错！");
		}finally{
			dbu.closeConnection(conn, pstat, rs);
		}
		return list;
	}

	public Role getById(int id) {
		Role role=new Role();
		try{
			String sql="select * from role where id=?";
			conn=dbu.getConnection();
			pstat=conn.prepareStatement(sql);
			pstat.setInt(1, id);
			rs=pstat.executeQuery();
			while(rs.next()){
				role.setId(rs.getInt("ID"));
				role.setName(rs.getString("NAME"));
			}
		}catch (Exception e) {
			System.out.println("根据role id返回role数据库连接出错！");
		}finally{
			dbu.closeConnection(conn, pstat, rs);
		}
		return role;
	}

	public Role getByName(String name) {
		Role role=new Role();
		try{
			String sql="select * from role where name=?";
			conn=dbu.getConnection();
			pstat=conn.prepareStatement(sql);
			pstat.setString(1, name);
			rs=pstat.executeQuery();
			while(rs.next()){
				role.setId(rs.getInt("ID"));
				role.setName(rs.getString("NAME"));
			}
		}catch (Exception e) {
			System.out.println("根据role name返回role数据库连接出错！");
		}finally{
			dbu.closeConnection(conn, pstat, rs);
		}
		return role;
	}

}
